package com.thinksns.sociax.t4.android.popupwindow;

import android.annotation.TargetApi;
import android.app.Activity;
import android.os.Build;
import android.support.annotation.NonNull;
import android.text.InputType;
import android.text.format.DateUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.PopupWindow;
import android.widget.TextView;

import com.prolificinteractive.materialcalendarview.CalendarDay;
import com.prolificinteractive.materialcalendarview.DayViewDecorator;
import com.prolificinteractive.materialcalendarview.DayViewFacade;
import com.prolificinteractive.materialcalendarview.MaterialCalendarView;
import com.prolificinteractive.materialcalendarview.OnDateSelectedListener;
import com.prolificinteractive.materialcalendarview.OnMonthChangedListener;
import com.prolificinteractive.materialcalendarview.OnRangeSelectedListener;
import com.thinksns.sociax.android.R;
import com.thinksns.sociax.t4.android.Thinksns;
import com.thinksns.sociax.t4.util.LogUtils;
import com.thinksns.sociax.thinksnsbase.network.ApiHttpClient;
import com.thinksns.sociax.unit.SociaxUIUtils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * Created by zhiyicx on 2017/5/9.
 */

public class EventDateWindow {
    private Activity activity;
    private OnDismissListener onDismissListener;
    private int animationStyle;
    private int width;
    private int height;
    private MaterialCalendarView calendarView;
    private PopupWindow mPopupWindow;
    private long time = 0;
    private String cid;
    private String area;
    private String wd;
    private long month;
    private int currentMonth;
    private int currentYear;
    private List<Integer> currentDay = new ArrayList<>();

    private EventDateWindow(Builder builder){
        activity = builder.activity;
        onDismissListener = builder.onDismissListener;
        animationStyle = builder.animationStyle;
        width = builder.width;
        height = builder.height;
        cid = builder.cid;
        area = builder.area;
        wd = builder.wd;
        initPop();
    }

    private void initPop(){

        View view = LayoutInflater.from(activity).inflate(R.layout.event_date_pop,null);
        calendarView = (MaterialCalendarView) view.findViewById(R.id.calendarView);

        calendarView.setAllowClickDaysOutsideCurrentMonth(false);

        Date date = new Date();
        month = date.getTime();

        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(date.getTime());
        calendarView.setCurrentDate(calendar);

        currentMonth = (calendar.get(Calendar.MONTH) + 1);
        currentYear = calendar.get(Calendar.YEAR);

        getEventDays();

        calendarView.setOnDateChangedListener(new OnDateSelectedListener() {
            @Override
            public void onDateSelected(@NonNull MaterialCalendarView widget, @NonNull CalendarDay date, boolean selected) {
                time = date.getCalendar().getTime().getTime()/1000l;
                dismiss();
            }
        });

        calendarView.setOnMonthChangedListener(new OnMonthChangedListener() {
            @Override
            public void onMonthChanged(MaterialCalendarView widget, CalendarDay date) {
                LogUtils.logE("setOnMonthChangedListener" + date.getYear() +date.getMonth()+date.getDay());
                currentMonth = date.getMonth() + 1;
                currentYear = date.getYear();
                month = date.getCalendar().getTime().getTime();
                getEventDays();
            }
        });

        mPopupWindow = new PopupWindow(view,width,height);
        mPopupWindow.setFocusable(true);
        mPopupWindow.setTouchable(true);
        mPopupWindow.setOutsideTouchable(false);
        if (animationStyle != 0) {
            mPopupWindow.setAnimationStyle(animationStyle);
        }
        mPopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                if(onDismissListener!=null){
                    onDismissListener.onDismiss(time);
                }
                setWindowNormal();
            }
        });
    }

    private void getEventDays(){
        calendarView.clearSelection();
        Thinksns.getApplication().getApiEvent().getEventDays(cid, area, Long.toString(month / 1000l),
                wd, new ApiHttpClient.HttpResponseListener() {
            @Override
            public void onSuccess(Object result) {

                String json = (String) result;
                LogUtils.logE("getEventDays success " + json);
                JSONObject jsonObject;
                try {
                    jsonObject  = new JSONObject(json);
                    Iterator<String> iterator = jsonObject.keys();
                    while(iterator.hasNext()){
                        currentDay.add(Integer.valueOf(iterator.next()));
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }

                for(int i = 0; i < currentDay.size();i++){
                    calendarView.setDateSelected(CalendarDay.from(currentYear,(currentMonth-1),currentDay.get(i)),true);
                }
                currentDay.clear();
            }

            @Override
            public void onError(Object result) {
                LogUtils.logE("getEventDays " + result);
            }
        });
    }

    protected void setWindowNormal() {
        setWindowAlpha(1.0f);
    }

    private void setWindowAlpha(float alpha) {
        WindowManager.LayoutParams params = activity.getWindow().getAttributes();
        params.alpha = alpha;
        params.verticalMargin = 100;
        activity.getWindow().setAttributes(params);
    }

    /**
     * 显示popWindow :相对于控件
     */
    @TargetApi(19)
    public void showPopAsDropDown(View parent, int offX, int offY, int gravity) {
        getEventDays();
        setWindowAlpha();
        // 设置popwindow显示位置
        try {
            mPopupWindow.showAsDropDown(parent, offX, offY, gravity);
        }catch (Throwable t){
            mPopupWindow.showAsDropDown(parent, offX, offY);
        }
        if (Build.VERSION.SDK_INT != 24)
            mPopupWindow.update();
        //startAnim();
    }

    public void showPopAsLocation(View parent, int offX, int offY, int gravity){
        setWindowAlpha();
        // 设置popwindow显示位置
        try {
            mPopupWindow.showAtLocation(parent, gravity, offX, offY);
        }catch (Throwable t){
            mPopupWindow.showAtLocation(parent, Gravity.CENTER, offX, offY);
        }
        if (Build.VERSION.SDK_INT != 24)
            mPopupWindow.update();
    }


    /**
     * 显示popWindow,在屏幕的最下方
     */
    public void showPopAtDown(View parent) {
        setWindowAlpha();
        // 设置popwindow显示位置
        mPopupWindow.showAtLocation(parent, Gravity.BOTTOM, 0, 0);
        if (Build.VERSION.SDK_INT != 24)
            mPopupWindow.update();
    }

    protected void setWindowAlpha() {
        setWindowAlpha(0.8f);
    }

    public void dismiss(){
        mPopupWindow.dismiss();
    }


    public interface OnDismissListener{
        void onDismiss(long time);
    }

    public static class Builder{
        private EventDateWindow popupWindow;
        private Activity activity;
        private OnDismissListener onDismissListener = new OnDismissListener() {
            @Override
            public void onDismiss(long time) {

            }
        };
        private int animationStyle = 0;
        private int width = ViewGroup.LayoutParams.WRAP_CONTENT;
        private int height = ViewGroup.LayoutParams.WRAP_CONTENT;
        private String cid;
        private String area;
        private String wd;


        public Builder(Activity mactivity){
            activity = mactivity;
        }

        public Builder setAnimationStyle(int s){
            this.animationStyle = s;
            return this;
        }

        public Builder setWidth(int s){
            this.width = s;
            return this;
        }

        public Builder setHeight(int s){
            this.height = s;
            return this;
        }

        public Builder setOnDismissListener(OnDismissListener listener){
            this.onDismissListener = listener;
            return this;
        }


        public EventDateWindow build(){
            popupWindow = new EventDateWindow(this);
            return popupWindow;
        }

        public Builder setCid(String cid) {
            this.cid = cid;
            return this;
        }

        public Builder setArea(String area) {
            this.area = area;
            return this;
        }

        public Builder setWd(String wd) {
            this.wd = wd;
            return this;
        }
    }

}
